<template>
<div>
  <header class="header">
<!--    <el-input  placeholder="" v-for="(item,index) in topInputList" :key="index" v-model="item.text" :placeholder="item.title" class="top-input"></el-input>-->
    <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
  </header>


  <div class="body">
    <el-table
      :data="tableData"
      border
      fit
      max-height="600"
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="100">
      </el-table-column>
      <el-table-column
        prop="user_name"
        label="账号"
        width="200">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号码"
        width="200">
      </el-table-column>
      <el-table-column
        prop="name"
        label="角色"
        >
      </el-table-column>
      <el-table-column
        label="操作"
        width="160"
        >
        <template slot-scope="scope">
          <el-button @click="checkOrder(scope.$index,scope.row)"  size="mini" >编辑</el-button>
          <el-button @click="deleteOrder(scope.$index,scope.row)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60,]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>


  <el-dialog
    :title.sync="dialogTitle"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose">
    <el-form :model="ruleForm"   :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="account">
        <div class="line">
          <el-input type="text" v-model="ruleForm.account" autocomplete="off" class="input"></el-input>
          <span class="span">字母数字或下划线,5-20位</span>
        </div>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input type="text" v-model="ruleForm.mobile"  autocomplete="off" class="input"></el-input>
      </el-form-item>
      <el-form-item label="密码" v-if='dialogTitle=="添加管理员"'prop="checkPass">
        <el-input type="password" v-model="ruleForm.checkPass" auto-complete="new-password" autocomplete="off" class="input"></el-input>
        <span class="span">请填写6到20位密码</span>
      </el-form-item>
      <el-form-item label="密码" v-else>
        <el-input type="password" v-model="ruleForm.checkPass" auto-complete="new-password" autocomplete="off" class="input"></el-input>
        <span class="span">请填写6到20位密码</span>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="role_id" placeholder="请选择" class="input">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
<!--        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>-->
<!--        <el-button @click="resetForm('ruleForm')">重置</el-button>-->
      </el-form-item>
    </el-form>






    <span slot="footer" class="dialog-footer">
    <el-button @click="closeDialog()">取 消</el-button>
    <el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
import {adminList,addAdmin, setAdmin, deleteAdmin, allList} from '../../../utils/api'
export default {
name: "Administrator",
  data(){
    var validatePass = (rule, value, callback) => {
      const regIdCard = /^\w{5,20}$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (regIdCard.test(value)) {
          callback();
        }else{
          callback(new Error('只能输入5-20位的数字或字母'));
        }
      }
    };
    var validatePass3 = (rule, value, callback) => {
      const regIdCard = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === '') {
        callback(new Error('请输入手机号'));
      }  else {
        if (regIdCard.test(value)) {
          callback();
        }else{
          callback(new Error('请输入正确的手机号'));
        }
      }
    };
    return{
      options: [
        {
          name:'请选择',
          id:'',
        }
      ],
      ruleForm: {
        account: '',
        checkPass: '',
        mobile: '',
      },
      rules: {
        account: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur'},
          {  min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        mobile: [
          { validator: validatePass3, trigger: 'blur' }
        ],
      },
      token:sessionStorage.getItem('token'),
      topInputList:[
        {title:'',text:''},
      ],
      loading:false,
      tableData: [],
      limit:10,
      currentPage:1,
      total:0,
      dialogTitle:'',
      dialogVisible: false,
      role_id:'',
      id:'',
   }
  },
  methods:{
    getList(){
    this.loading = true
    adminList(this.token,this.currentPage,this.limit).then(res=>{
      if(res.data.status){
        this.tableData = res.data.data.data
        this.total = res.data.data.count
        console.log(this.tableData)
        let timer = setTimeout(()=>{
          this.loading = false
          clearTimeout(timer)
        },400)


      }else{
        if(res.data.msg =="token失效,请重新进行登录"){
          this.$router.push("/login");
        }
        let timer = setTimeout(()=>{
          this.$message.error(res.data.msg);
          this.loading = false
        },400)
      }
    }).catch(err=>{
      this.$message.error(err.data.data);
    })
  },
    add(){
      this.dialogVisible = true
      this.dialogTitle = '添加管理员'
    },
    getroleList(){
      allList(this.token).then(res=>{
        if(res.data.status){
          if(res.data.status){
            this.options = this.options.concat(res.data.data.data)
            console.log(this.options,res.data.data.data)
          }
        }else{
          this.$message.error(res.data.msg)
        }
      })
    },
    handleSelectionChange(){

    },
    checkOrder(index,row){
      console.log(row)
      this.ruleForm = {
        account: row.user_name,
        checkPass: '',
        mobile: row.phone,
      }
      this.role_id = row.role_id
      this.id = row.id
      this.dialogTitle = '编辑管理员'
      this.dialogVisible = true
    },
    deleteOrder(index,row){
      this.$confirm('此操作将删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.id = row.id
        deleteAdmin(this.token,this.id).then(res=>{
          if(res.data.status){
            this.id = ''
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }else{
            this.$message.error(res.data.msg)
          }
        })

      }).catch(() => {
        this.id = ''
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    handleSizeChange(val) {
      this.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.ruleForm = {
            account: '',
            checkPass: '',
            mobile: '',
          }
          this.id = ''
          this.role_id = ''
          this.$refs.ruleForm.resetFields();
        })
        .catch(_ => {});
    },
    closeDialog(){
      this.$refs.ruleForm.resetFields();
      this.ruleForm = {
        account: '',
        checkPass: '',
        mobile: '',
      }
      this.role_id = ''
      this.id = ''
      this.dialogVisible = false
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle=='添加管理员'){
            addAdmin(this.token,this.ruleForm.account,this.ruleForm.checkPass,this.ruleForm.mobile,this.role_id).then(res=>{
              if(res.data.status){
                console.log(res.data.data)
                this.$message({
                  message: '操作成功',
                  type: 'success',
                });
                this.ruleForm = {
                  account: '',
                  checkPass: '',
                  mobile: '',
                },
                  this.dialogVisible = false
                this.getList()
              }else{
                this.$message.error(res.data.msg)
              }
            })
            return
          }else{
            setAdmin(this.token,this.ruleForm.account,this.ruleForm.checkPass,this.ruleForm.mobile,this.role_id,this.id).then(res=>{
                console.log(res.data)
              if(res.data.status){
                this.$message({
                  message: '操作成功',
                  type: 'success',
                });
                this.ruleForm = {
                  account: '',
                  checkPass: '',
                  mobile: '',
                },
                this.dialogVisible = false
                this.getList()
              }else{
                this.$message.error(res.data.msg)
              }
            })
          }


        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }



  },
  mounted() {
    this.getList()
    this.getroleList()
  },
  watch:{
    role_id(n,o){
      if(n==''){
        this.role_id = ''
      }
    },
  }
}
</script>

<style scoped>
.demo-ruleForm{
  width: 80%;
}

.demo-ruleForm .span{
  color: #999999;
  margin-left: 10px;
}
/deep/.header{
  background: white!important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}
.top-input{
  width: 150px;
  margin-right: 20px;
}
.body{
  margin: 20px 0;
}
/deep/.el-table th.el-table__cell>.cell{
  text-align: center;
}
/deep/.el-table .cell{
  text-align: center;
}
.input{
  width: 45%;
}
</style>
